﻿using Newtonsoft.Json;
using System;
using System.Configuration;
using System.IO;
using WMS.Core;

namespace WMS.Configuration
{
    public abstract class BaseConfiguration<T>
        where T : class, new()
    {
        private static readonly object mutex = new object();

        private static T instance = null;

        public static T Instance
        {
            get
            {
                lock (mutex)
                {
                    LoadConfigFile();
                    return instance;
                }
            }
        }

        private static string EnvKey
        {
            get
            {
#if _DEBUG_
                return ".Development";
#elif _TEST_
                return ".Test";
#else
                return "";
#endif
            }
        }

        private static string GetConfigFilePath()
        {
            string ConfigFilePath = ConfigurationManager.AppSettings[nameof(ConfigFilePath)];
            ConfigFilePath = ConfigFilePath.Replace("{$Env}", EnvKey);
            var ret = Path.GetFullPath(ConfigFilePath);
            return ret;
        }

        private static void LoadConfigFile()
        {
            if (instance != null)
            {
                return;
            }

            try
            {
                var path = GetConfigFilePath();
                var json = File.ReadAllText(path);
                var settings = JsonConvert.DeserializeObject<T>(json);
                instance = settings;
            }
            catch (Exception)
            {
                instance = new T();
            }
        }

        public static void Save()
        {
            try
            {
                if (instance == null)
                {
                    throw new Exception("配置文件未加载.");
                }
                string path = GetConfigFilePath();
                var json = JsonConvert.SerializeObject(instance, Formatting.Indented);
                File.WriteAllText(path, json);
            }
            catch (Exception ex)
            {
                Logs.Instance.Out(ex, "配置参数保存失败.");
            }
        }

    }
}
